package Core
{	
	import Core.ILoadable;
	
	import flash.display.DisplayObject;
	import flash.net.SharedObject;
	
	
	import mx.core.Application;
	import mx.core.IFlexDisplayObject;
	import mx.managers.PopUpManager;
	
	import utils.Trace;

	public class Storage 
	{
		
		private var mySO:SharedObject;
		private var _saveObj:Object;
		private var _callingDisplayObject:DisplayObject;
		private var _iLoader:ILoadable; // Callback to return the storage object
		private var _fileType:String;
		
		public function Storage( dispObj:DisplayObject, iLoader:ILoadable, fileType:String) {
			this._callingDisplayObject = dispObj;
			if( this._callingDisplayObject == null ){
				Trace.throwError("callingDisplayObject == null");
			}
			this._iLoader = iLoader;
			this._fileType = fileType; // Tuck it here for debugging. Never use it after opening the SO
			mySO = SharedObject.getLocal(fileType);
//			mySO.clear(); // Get rid of all data
			if( mySO.size == 0){
				this._iLoader.saveBeginningFiles( this );
			}
		}
		// Called by LoadDialog
		//
		public function loadNamedFile( fileName:String ):void {
			trace("Storage.loadNamedFile: "+fileName);
			var obj:*;
			fileName = fileName.toLowerCase();
			this.currentFileName = fileName;
			obj = mySO.data[ fileName];
			if( obj == null){
				Trace.throwError( "no CW loaded");
			}
			this._iLoader.plugData( obj );
		}
		// calls up Dialog to allow named save
		public function write( obj:Object):void {
			this._saveObj = obj;
			if( obj == null){
				Trace.throwError("object == null");
			}
			var sd:SaveDialog =
          	    SaveDialog(PopUpManager.createPopUp( this._callingDisplayObject, SaveDialog, true));
          	sd.initDialog( this, this.currentFileName  );
  		}
  		public function set currentFileName( fn:String ):void {
  			// set public variable on app - currentchipwit, currentmission, currentplayer
  			Application.application[ "current"+ this._fileType ] = fn;
  		}
 		public function get currentFileName( ):String {
			return Application.application[ "current"+ this._fileType ];
 		}
 		// Called by SaveDialog
		public function doWrite( fileName:String ):void {
			fileName = fileName.toLowerCase();
			this.currentFileName = fileName ;
			doWriteObject( fileName, this._saveObj);
		}
		public function doWriteObject( fileName:String, fileObj:Object ):void{
			fileName = fileName.toLowerCase();
			mySO.data[ fileName] = fileObj;
			mySO.flush();
		}
		public function allFiles():Array {
			var arr:Array = new Array();
			var fileName:String; 
			for( var n:String in mySO.data ){
				// Strip off the fileType, which is terminated by a "-"
				fileName = n.slice( n.indexOf("-") + 1);
				arr.push( fileName );
			}
			return arr;
		}
	}
}
